package com.hs.chd.action.search;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hs.chd.helper.ChangeCharset;
import com.hs.chd.helper.SQLHelper;
import com.hs.chd.model.SchdChnpaper;
import com.hs.chd.model.Searchmview;
import com.hs.chd.service.ISearchService;
import com.hs.core.action.BaseAction;
import com.hs.core.db.DBMgr;
import com.hs.core.db.QueryPage;
import com.hs.core.utils.SystemUtil;
@Controller  
public class SearchController  extends BaseAction {
    /**
	 * 
	 */
	private static final long serialVersionUID = -354434172898440670L;
	private static final Logger logger = Logger.getLogger(SearchController.class);
	private static Map CONSTANTMAP = new HashMap();
	private ISearchService searchService;
	@Autowired  
	public void setSearchService(ISearchService searchService) {
		this.searchService = searchService;
	}
	 @RequestMapping(value="/search/test.do")   
	    public void test(HttpServletRequest request,
					HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         DBMgr dbo = this.getDbo(request);
         String params = request.getParameter("paramnames");
         //logger.debug("params:" + params);
         SQLHelper helper = new SQLHelper();
         Map pmap = helper.initParams(request, params);
         String allsql = helper.processSql(pmap);
         logger.debug("allsql:" + allsql);
         
         
         
	         //Map treedata = getTreeStr(dbo);
	        // modelMap.addAllAttributes(treedata);
			// return new ModelAndView("app/search/abstractlist",modelMap);
			 //return new ModelAndView("app/search/searchIndex",modelMap);
			 
		 } 
	 /**
	  * 检索首页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/searchIndex.do")   
	    public ModelAndView searchIndex(HttpServletRequest request,
					HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
      
			return new ModelAndView("app/search/searchIndex",modelMap);
			 
		 } 
//	 /**
//	  * 异步检索
//	  * @param request
//	  * @param response
//	  * @param modelMap
//	  * @return
//	  * @throws ServletException
//	  * @throws IOException
//	  */
//	 @RequestMapping(value="/search/dosearch.do", method = RequestMethod.POST)   
//	    public void dosearch(HttpServletRequest request,
//					HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
//		 String sql = "select id,TITLE,TITLEn from SEARCHMVIEW where datatype=1";
//         String params = request.getParameter("paramnames");
//         System.out.println("params:" + params);
//         System.out.println("params:" + request.getParameter("txt_3_sel"));
//         
//		 SQLHelper helper = new SQLHelper();
//         Map pmap = helper.initParams(request, params);
//         String allsql = helper.processSql(pmap);
//         logger.debug("allsql:" + allsql);
//		 QueryPage qp = new QueryPage(request,request.getContextPath()+"/search/dosearch.do",sql,new HashMap()); 
//	     qp.query();  
//	     List datalist = qp.getDataList();
//	     StringBuffer htmlBuffer = new StringBuffer();
//	     for(int i =0;i<datalist.size();i++){
//	    	 Map rowdata = (Map)datalist.get(i);
//	    	 String idstr = rowdata.get("id")+"";
//	    	 String title = (String)rowdata.get("TITLE");
//	    	 String titlen = (String)rowdata.get("TITLEN");
//	    	 htmlBuffer.append("<tr>");
//	    	 htmlBuffer.append("<td>");
//	    	 htmlBuffer.append(idstr);
//	    	 htmlBuffer.append("</td>");
//	    	 htmlBuffer.append("<td>");
//	    	 htmlBuffer.append(title);
//	    	 htmlBuffer.append("</td>");
//	    	 htmlBuffer.append("<td>");
//	    	 htmlBuffer.append(titlen);
//	    	 htmlBuffer.append("</td>");
//	    	 htmlBuffer.append("</tr>"); 
//	     }
//	     PrintWriter out = response.getWriter();
//	     out.print(htmlBuffer.toString());
//	     out.flush();
//	     out.close();
//			//return new ModelAndView("app/search/searchIndex",modelMap); 
//		} 
//	 /**
//	  * 文献检索列表形式
//	  * @param request
//	  * @param response
//	  * @param modelMap
//	  * @return
//	  * @throws ServletException
//	  * @throws IOException
//	  */
	 @RequestMapping(value="/search/index.do")   
    public ModelAndView index(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         //DBMgr dbo = this.getDbo(request);
         //Map treedata = getTreeStr(dbo);
        // modelMap.addAllAttributes(treedata);
		 //return new ModelAndView("app/search/abstractlist",modelMap);
		 return new ModelAndView("app/search/searchIndex",modelMap);
		 
	 } 
//	 /**
//	  * 检索页面
//	  * @param request
//	  * @param response
//	  * @param modelMap
//	  * @return
//	  * @throws ServletException
//	  * @throws IOException
//	  */
//	 @RequestMapping(value="/search/datalistindex.do")   
//    public ModelAndView datalistindex(HttpServletRequest request,
//				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
//         //DBMgr dbo = this.getDbo(request);
//         //Map treedata = getTreeStr(dbo);
//        // modelMap.addAllAttributes(treedata);
//		 return new ModelAndView("app/search/abstractlist",modelMap);
//		 
//	 } 
	 /**
	  * 文献检索入口
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/dosearch.do")   
    public ModelAndView dosearch(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 //排序
 		 String searchtype = request.getParameter("searchtype");
 		 if(StringUtils.isEmpty(searchtype)){
 			searchtype = "basic_search";
 		 }
 		 request.setAttribute("searchtype", searchtype);
 		 ModelAndView mv = new ModelAndView(); 
		 if("advsearch".equals(searchtype)){
			mv = advSearch(request, response,modelMap);
		 }else{
			mv = basicSearch(request, response,modelMap);
		 } 
		 //String pstr = processParameter(request);
		// logger.debug("pstr:" + pstr);
		 //mv.getModelMap().put("paramstr", pstr);
		 return mv;
		 
	 } 
//	 /**
//	  * 接收表单提交的参数，构成字符串
//	  * @param request
//	  * @return
//	  */
//	 private static String processParameter(HttpServletRequest request){
//		 StringBuffer buffer = new StringBuffer();
//		 Map parammap = request.getParameterMap();
//		 if(parammap != null && !parammap.isEmpty()){
//			 Set pset = parammap.entrySet();
//			 Iterator iter = pset.iterator();
//			 while(iter.hasNext()){
//				 Entry entry = (Entry)iter.next();
//				 String key = (String)entry.getKey();
//				 String[] value = (String[])entry.getValue(); 
//				// String value =  entry.getValue()+"";
//				 buffer.append("&").append(key).append("=").append(value[0]);
//			 }
//		 }
//		 return buffer.toString();
//	 }
	 /**
	  * 全库基本检索
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	 * @throws UnsupportedEncodingException 
	  */
	 private ModelAndView basicSearch(HttpServletRequest request,
		 HttpServletResponse response,ModelMap modelMap) throws UnsupportedEncodingException{
		 request.setCharacterEncoding("UTF-8");
		 Map paramMap = this.basicSearchPrepare(request);
		 String basiccol = (String)paramMap.get("basiccol");
		 String basicvalue = (String)paramMap.get("basicvalue");
		 String basicspecial = (String)paramMap.get("basicspecial");
		 String orderName = (String)paramMap.get("orderName");
		 String orderNum = (String)paramMap.get("orderNum");
		 String datatype = (String)paramMap.get("datatype");
		 String keyword = (String)paramMap.get("keyword");
		 StringBuffer allfullsql = (StringBuffer)paramMap.get("allfullsql");
		 String onekeyword = (String)paramMap.get("onekeyword");
		 String onesearchinfo = (String)paramMap.get("onesearchinfo");
		 String qstr = request.getQueryString();
		 System.out.println("qstr:"+qstr);
//		 String basiccol = request.getParameter("basiccol");//字段列名
//		 String basicvalue = request.getParameter("basicvalue");//字段值
//		 String basicspecial = request.getParameter("basicspecial");//查询方式：精确，模糊
// 		 String orderName = request.getParameter("orderName");//排序字段
//		 String orderNum = request.getParameter("orderNum");//排序方式
//		 String onesql = request.getParameter("onesql");//一次检索sql 
//		 String datatype = request.getParameter("datatype");//数据范围
//		 String onekeyword = request.getParameter("onekeyword");//二次检索中第一次的检索词
//		 String onesearchinfo = request.getParameter("onesearchinfo");//二次检索中第一次的检索词
//		 String issyn = request.getParameter("issyn");//二次检索中第一次的检索词
//  		 request.setAttribute("orderName", orderName); 
//		 request.setAttribute("orderNum", orderNum); 
//		 String distype = request.getParameter("distype");//疾病类型
//		 String startyear = request.getParameter("startyear");//起始年份
//		 String endyear = request.getParameter("endyear");//起始年份 
//		 StringBuffer orderByStr = new StringBuffer(" order by ");
//		 if(StringUtils.isNotBlank(orderName)){
//		    	if("1".equals(orderNum)){
//		    		orderByStr.append(orderName).append(" asc");
//		    	}
//		    	if("2".equals(orderNum)){
//		    		orderByStr.append(orderName).append(" desc");
//		    	}
//		  }else{
//		    	orderByStr.append("a.title").append(" desc");
//		    	orderName = "a.title";
//		    	orderNum = "2";
//		  }
//		 StringBuffer allfullsql= new StringBuffer();
//		 String keyword = null;
//		 if(StringUtils.isEmpty( datatype)){
//			 //0 代表全部三种数据类型
//			 datatype = "0";
//		 }
//		 allfullsql.append("select a.* from SEARCHMVIEW a where 1=1    ");
//		 if(StringUtils.isNotEmpty(datatype)){
//			 if(!"0".equals(datatype)){
//				 allfullsql.append("  and  a.DATATYPE=").append(datatype);
//			 } 
//		 }
//		 if(StringUtils.isNotEmpty(distype)){
//			 if(!"0".equals(distype)){
//				 allfullsql.append("  and  a.DISNAME='").append(distype).append("' ");
//			 } 
//		 }
//		 if(StringUtils.isNotEmpty(startyear)){
//			 allfullsql.append("  and  to_date(substr(a.YEARSTR,0,4),'yyyy')>=").append("to_date("+startyear+",'yyyy') ");
//		 }
//		 if(StringUtils.isNotEmpty(endyear)){
//			 allfullsql.append("  and  to_date(substr(a.YEARSTR,0,4),'yyyy')<=").append("to_date("+endyear+",'yyyy') ");
//		 }
//		 if(StringUtils.isNotEmpty(basicvalue)){
//			 keyword = basicvalue;
//			 if("0".equals(basicspecial)){
//				 if("TITLE".equals(basiccol)){
//					 allfullsql.append(" and (lower(a.").append(basiccol).append(")=lower('").append(basicvalue.trim()).append("')");
//					 allfullsql.append(" or lower(a.TITLEN) =lower('").append(basicvalue.trim()).append("'))");
//				 }else if("ORIGINALTEXT".equals(basiccol)||"ABSTRACT".equals(basiccol)){
//					 allfullsql.append(" and lower(a.").append("ABSTRACT)").append("=lower('").append(basicvalue.trim()).append("')");
//					 //allfullsql.append(" or lower(a.ORIGINALTEXT) =lower('").append(basicvalue.trim()).append("'))");
//				 }else if("ALL".equals(basiccol)){//任意字段检索
//					 allfullsql.append(allColumnsearch(basicvalue,basicspecial));
//				 }
//				 //由于没有同义词关联，只能查询两个
////				 else if("DISNAME".equals(basiccol)){//疾病名称检索
////					 if("1".equals(issyn)){
////						 allfullsql.append(" and a.DATATYPE=1  and a.DISNAME in ( ");
////						 allfullsql.append(" select C.RIGHTNAME  from   SCHD_STANDWORD C WHERE   C.OTHERNAME = '"+basicvalue.trim()+"'");
////						 
////						 allfullsql.append(" UNION all select C.OTHERNAME  from   SCHD_STANDWORD C WHERE   C.RIGHTNAME =  = '"+basicvalue.trim()+"')"); 
////						
////					 }else{
////						 allfullsql.append(" and a.id in (select PAPERID from CHD_PAPERTAGS where tagid in(");
////						 allfullsql.append(" SELECT id FROM CHD_TAGS WHERE  TAGNAME = '"+basicvalue.trim()+"'))");
////					 }
//// 				 }
//				 else{
//					  //String colname = CONSTANTMAP.get(basiccol)+""; 
//				      //searchbuffer.append(colname).append("“").append(basicvalue).append("”").append("&nbsp;"); 
//
//					 allfullsql.append(" and lower(a.").append(basiccol).append(")=lower('").append(basicvalue.trim()).append("')");
//				 }
//				 
//			 }else if("1".equals(basicspecial)){
//				 if("TITLE".equals(basiccol)){
//					 allfullsql.append(" and (lower(a.").append(basiccol).append(") like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
//					 allfullsql.append(" or lower(a.TITLEN) like '%'||lower('").append(basicvalue.trim()).append("')||'%')");
// 
//				 }else if("PERIODICALNAME".equals(basiccol)||"BOOKNAME".equals(basiccol)){
//					 allfullsql.append(" and lower(a.").append("PERIODICALNAME").append(") like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
//  
//				 }else if("ABSTRACT".equals(basiccol)||"ORIGINALTEXT".equals(basiccol)){
//					 allfullsql.append(" and lower(a.").append("ABSTRACT)").append(" like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
//					// allfullsql.append(" or lower(a.ORIGINALTEXT) like '%'||lower('").append(basicvalue.trim()).append("')||'%')");
// 
//				 }
////				 else if("DISNAME".equals(basiccol)){//疾病名称检索
////					 if("1".equals(issyn)){
////						 allfullsql.append(" and a.DATATYPE=1   and a.DISNAME in ( ");
////						 allfullsql.append(" UNION all select C.RIGHTNAME  from   SCHD_STANDWORD C WHERE   C.OTHERNAME like '%"+basicvalue.trim()+"%')");
////						 allfullsql.append(" UNION all SELECT id from CHD_TAGS WHERE TAGNAME LIKE '%"+basicvalue.trim()+"%')");
////					 }else{
////						 allfullsql.append(" and a.id in (select PAPERID from CHD_PAPERTAGS where tagid in(");
////						 allfullsql.append(" SELECT id FROM CHD_TAGS WHERE TAGNAME LIKE '%"+basicvalue.trim()+"%'))");
////					 }
//// 				 }
//				 else if("ALL".equals(basiccol)){//任意字段检索
//					 allfullsql.append(allColumnsearch(basicvalue,basicspecial));
// 				 }else{
//					  String colname = CONSTANTMAP.get(basiccol)+"";  
//					  allfullsql.append(" and lower(a.").append(basiccol).append(") like '%'||lower('").append(basicvalue.trim()).append("')||'%' ");
//				 }
//			 }
//		 } 
//		
//		 if(StringUtils.isNotEmpty(onesql)){
//			 onesql = "select id from(" + onesql + ")";
//			 allfullsql.append(" and a.id in (");
//			 allfullsql.append(onesql);
//			 allfullsql.append(")");
//			 if(null!= keyword){
//				 keyword += "|"+onekeyword;
//			 }else{ 
//			 	 keyword = onekeyword;
//			 }
//		 }else{
//			 onekeyword = keyword;
//		 }
//		 allfullsql.append(orderByStr);
		 Map conditionmap = new HashMap();
         conditionmap.put("orderName", orderName);
         conditionmap.put("orderNum", orderNum); 
         conditionmap.put("basiccol", basiccol); 
         conditionmap.put("basicvalue", basicvalue); 
         conditionmap.put("basicspecial", basicspecial); 
         conditionmap.put("searchtype", "basic_search"); 
         conditionmap.put("datatype", datatype);
         conditionmap.put("onekeyword", onekeyword); 
         conditionmap.put("onesearchinfo", onesearchinfo);
         conditionmap.put("keyword", keyword);
        
         logger.debug("allfullsql:" + allfullsql);
 		 QueryPage qp = new QueryPage(request,request.getContextPath()+"/search/dosearch.do",allfullsql.toString(),conditionmap); 
	     qp.query();  
	     String pagenum =  qp.getCurrentPageNo() + "";
	     String pagecount = qp.getPerPageCount() + "";
	     modelMap.put("pagenum", pagenum); 
	     modelMap.put("pagecount", pagecount);
	     modelMap.put("pagestr", qp.getPageStr());
	     modelMap.put("datalist", qp.getDataList());
	     modelMap.put("onesql", allfullsql.toString()); 
	     modelMap.put("onekeyword", keyword); 
	     modelMap.put("searchtype", "basic_search"); 
	     modelMap.put("datatype", datatype);  
	     modelMap.put("onesearchinfo", onesearchinfo);
	     modelMap.put("keyword", keyword);
	     DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
	     String groupsql = "select datatype,count(*) as countnum from (" + qp.getSearchSql() + ") group by datatype"; 
	     List groupList = dbo.queryList(groupsql, null);
	     Map groupMap = new HashMap();
	     for(int j = 0;j<groupList.size();j++){
	    	 Map data = (Map)groupList.get(j);
	    	 String key = (String)data.get("datatype");
	    	 String count = data.get("countnum")+"";
	    	 groupMap.put(key, count);
	    	 
	     }
	     ChangeCharset test = new ChangeCharset();
	     
	     modelMap.put("continfo", groupMap);
	     modelMap.put("allfullsql", test.toUTF_8(qstr)); 
  		return new ModelAndView("app/search/resultlist",modelMap);
	 }
     private Map basicSearchPrepare(HttpServletRequest request){
    	 Map param = new HashMap();
    	 String basiccol = request.getParameter("basiccol");//字段列名
		 String basicvalue = request.getParameter("basicvalue");//字段值
		 String basicspecial = request.getParameter("basicspecial");//查询方式：精确，模糊
 		 String orderName = request.getParameter("orderName");//排序字段
		 String orderNum = request.getParameter("orderNum");//排序方式
		 String onesql = request.getParameter("onesql");//一次检索sql 
		 String disnamestr = request.getParameter("disnamestr");//一次检索sql 
		 String datatype = request.getParameter("datatype");//数据范围
		 String onekeyword = request.getParameter("onekeyword");//二次检索中第一次的检索词
		 String onesearchinfo = request.getParameter("onesearchinfo");//二次检索中第一次的检索词
		 String issyn = request.getParameter("issyn");//二次检索中第一次的检索词
  		 request.setAttribute("orderName", orderName); 
		 request.setAttribute("orderNum", orderNum); 
 		 String startyear = request.getParameter("startyear");//起始年份
		 String endyear = request.getParameter("endyear");//起始年份 
		 StringBuffer orderByStr = new StringBuffer(" order by ");
		 if(StringUtils.isNotBlank(orderName)){
		    	if("1".equals(orderNum)){
		    		orderByStr.append(orderName).append(" asc");
		    	}
		    	if("2".equals(orderNum)){
		    		orderByStr.append(orderName).append(" desc");
		    	}
		  }else{
		    	orderByStr.append("a.id").append(" desc");
		    	orderName = "a.id";
		    	orderNum = "2";
		  }
		 StringBuffer allfullsql= new StringBuffer();
		 String keyword = null;
		 if(StringUtils.isEmpty( datatype)){
			 //0 代表全部三种数据类型
			 datatype = "0";
		 }
		 allfullsql.append("select a.* from SEARCHMVIEW a where 1=1    ");
		 if(StringUtils.isNotEmpty(datatype)){
			 if(!"0".equals(datatype)){
				 allfullsql.append("  and  a.DATATYPE=").append(datatype);
			 } 
		 }
		 if(StringUtils.isNotEmpty(disnamestr)){
			 String[] disnamearr = disnamestr.split(",");
			 if(null != disnamearr && disnamearr.length == 1){
				 allfullsql.append("  and  a.DISNAME='").append(disnamearr[0]).append("' ");
			 }
			 if(null != disnamearr && disnamearr.length == 2){
				 allfullsql.append("  and  (a.DISNAME='").append(disnamearr[0]).append("' ");
				 allfullsql.append("  or  a.DISNAME='").append(disnamearr[1]).append("') ");
			 }
			  
		 }
		 if(StringUtils.isNotEmpty(startyear)){
			 allfullsql.append("  and  to_date(substr(a.YEARSTR,0,4),'yyyy')>=").append("to_date("+startyear+",'yyyy') ");
		 }
		 if(StringUtils.isNotEmpty(endyear)){
			 allfullsql.append("  and  to_date(substr(a.YEARSTR,0,4),'yyyy')<=").append("to_date("+endyear+",'yyyy') ");
		 }
		 if(StringUtils.isNotEmpty(basicvalue)){
			 keyword = basicvalue;
			 if("0".equals(basicspecial)){
				 if("TITLE".equals(basiccol)){
					 allfullsql.append(" and (lower(a.").append(basiccol).append(")=lower('").append(basicvalue.trim()).append("')");
					 allfullsql.append(" or lower(a.TITLEN) =lower('").append(basicvalue.trim()).append("'))");
				 }else if("ORIGINALTEXT".equals(basiccol)||"ABSTRACT".equals(basiccol)){
					 allfullsql.append(" and lower(a.").append("ABSTRACT)").append("=lower('").append(basicvalue.trim()).append("')");
					 //allfullsql.append(" or lower(a.ORIGINALTEXT) =lower('").append(basicvalue.trim()).append("'))");
				 }else if("ALL".equals(basiccol)){//任意字段检索
					 allfullsql.append(allColumnsearch(basicvalue,basicspecial));
				 }
				 //由于没有同义词关联，只能查询两个
//				 else if("DISNAME".equals(basiccol)){//疾病名称检索
//					 if("1".equals(issyn)){
//						 allfullsql.append(" and a.DATATYPE=1  and a.DISNAME in ( ");
//						 allfullsql.append(" select C.RIGHTNAME  from   SCHD_STANDWORD C WHERE   C.OTHERNAME = '"+basicvalue.trim()+"'");
//						 
//						 allfullsql.append(" UNION all select C.OTHERNAME  from   SCHD_STANDWORD C WHERE   C.RIGHTNAME =  = '"+basicvalue.trim()+"')"); 
//						
//					 }else{
//						 allfullsql.append(" and a.id in (select PAPERID from CHD_PAPERTAGS where tagid in(");
//						 allfullsql.append(" SELECT id FROM CHD_TAGS WHERE  TAGNAME = '"+basicvalue.trim()+"'))");
//					 }
// 				 }
				 else{
					  //String colname = CONSTANTMAP.get(basiccol)+""; 
				      //searchbuffer.append(colname).append("“").append(basicvalue).append("”").append("&nbsp;"); 

					 allfullsql.append(" and lower(a.").append(basiccol).append(")=lower('").append(basicvalue.trim()).append("')");
				 }
				 
			 }else if("1".equals(basicspecial)){
				 if("TITLE".equals(basiccol)){
					 allfullsql.append(" and (lower(a.").append(basiccol).append(") like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
					 allfullsql.append(" or lower(a.TITLEN) like '%'||lower('").append(basicvalue.trim()).append("')||'%')");
 
				 }else if("PERIODICALNAME".equals(basiccol)||"BOOKNAME".equals(basiccol)){
					 allfullsql.append(" and lower(a.").append("PERIODICALNAME").append(") like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
  
				 }else if("ABSTRACT".equals(basiccol)||"ORIGINALTEXT".equals(basiccol)){
					 allfullsql.append(" and lower(a.").append("ABSTRACT)").append(" like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
					// allfullsql.append(" or lower(a.ORIGINALTEXT) like '%'||lower('").append(basicvalue.trim()).append("')||'%')");
 
				 }
//				 else if("DISNAME".equals(basiccol)){//疾病名称检索
//					 if("1".equals(issyn)){
//						 allfullsql.append(" and a.DATATYPE=1   and a.DISNAME in ( ");
//						 allfullsql.append(" UNION all select C.RIGHTNAME  from   SCHD_STANDWORD C WHERE   C.OTHERNAME like '%"+basicvalue.trim()+"%')");
//						 allfullsql.append(" UNION all SELECT id from CHD_TAGS WHERE TAGNAME LIKE '%"+basicvalue.trim()+"%')");
//					 }else{
//						 allfullsql.append(" and a.id in (select PAPERID from CHD_PAPERTAGS where tagid in(");
//						 allfullsql.append(" SELECT id FROM CHD_TAGS WHERE TAGNAME LIKE '%"+basicvalue.trim()+"%'))");
//					 }
// 				 }
				 else if("ALL".equals(basiccol)){//任意字段检索
					 allfullsql.append(allColumnsearch(basicvalue,basicspecial));
 				 }else{
					  String colname = CONSTANTMAP.get(basiccol)+"";  
					  allfullsql.append(" and lower(a.").append(basiccol).append(") like '%'||lower('").append(basicvalue.trim()).append("')||'%' ");
				 }
			 }
		 } 
		
		 if(StringUtils.isNotEmpty(onesql)){
			 onesql = "select id from(" + onesql + ")";
			 allfullsql.append(" and a.id in (");
			 allfullsql.append(onesql);
			 allfullsql.append(")");
			 if(null!= keyword){
				 keyword += "|"+onekeyword;
			 }else{ 
			 	 keyword = onekeyword;
			 }
		 }else{
			 onekeyword = keyword;
		 }
		 allfullsql.append(orderByStr);
		 param.put("allfullsql", allfullsql);
		 param.put("basiccol", basiccol);
		 param.put("basicvalue", basicvalue);
		 param.put("basicspecial", basicspecial);
		 param.put("orderName", orderName);
		 param.put("orderNum", orderNum);
		 param.put("datatype", datatype);
		 param.put("keyword", keyword);
		 param.put("onekeyword", onekeyword); 
		 param.put("onesearchinfo", onesearchinfo);
		 
		 return param;
     }
	 /**
	  * 任意字段sql拼接
	  * @return
	  */
	 private static String allColumnsearch(String basicvalue ,String searchtype){
		 StringBuilder builder = new StringBuilder();
		 if("1".equals(searchtype)){
	 		 //标题、关键词、主题词、摘要/原文文本化、刊名、英文刊名、书籍名称、年份/朝代、期、基金、资助类别\作者、英文作者
			 builder.append(" and (lower(a.TITLE").append(") like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			 builder.append(" or lower(a.TITLEN) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
	 		 builder.append(" or lower(a.").append("PERIODICALNAME").append(")like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			// builder.append(" or lower(a.PERIODICALNAMEENG) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			 //builder.append(" or lower(a.BOOKNAME) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
	 		 builder.append(" or lower(a.").append("ABSTRACT)").append("like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			 //builder.append(" or lower(a.ABSTRACTENG) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			// builder.append(" or lower(a.ORIGINALTEXT) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
	 		 builder.append(" or lower(a.").append("SUBJECTWORD)").append(" like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			 //builder.append(" or lower(a.SUBJECTWORDENG) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
	  		 builder.append(" or lower(a.").append("KEYWORD)").append(" like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			// builder.append(" or lower(a.KEYWORDENG) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			 builder.append(" or lower(a.AUTHOR) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			// builder.append(" or lower(a.YEARSTR) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			 //builder.append(" or lower(a.AUTHORUNIT) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			// builder.append(" or lower(a.AUTHORADDRESS) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");

			 builder.append(" or lower(a.PERIOD) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			 builder.append(" or lower(a.BOOKCD) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			 builder.append(" or lower(a.FUNDNAME) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			 builder.append(" or lower(a.FUNDTYPE) like '%'||lower('").append(basicvalue.trim()).append("')||'%'");
			 builder.append(" or lower(a.TCMNAME) like '%'||lower('").append(basicvalue.trim()).append("')||'%')"); 

		 }else if("0".equals(searchtype)){
			  
	 		 //标题、关键词、主题词、摘要/原文文本化、刊名、英文刊名、书籍名称、年份/朝代、期、基金、资助类别\作者、英文作者
			 builder.append(" and (lower(a.TITLE").append(")=lower('").append(basicvalue.trim()).append("')");
			 builder.append(" or lower(a.TITLEN) =lower('").append(basicvalue.trim()).append("')");
	 		 builder.append(" or lower(a.").append("PERIODICALNAME").append(")=lower('").append(basicvalue.trim()).append("')");
			// builder.append(" or lower(a.PERIODICALNAMEENG) =lower('").append(basicvalue.trim()).append("')");
			// builder.append(" or lower(a.BOOKNAME) =lower('").append(basicvalue.trim()).append("')");
	 		 builder.append(" or lower(a.").append("ABSTRACT)").append("=lower('").append(basicvalue.trim()).append("')");
			// builder.append(" or lower(a.ABSTRACTENG) =lower('").append(basicvalue.trim()).append("')");
			// builder.append(" or lower(a.ORIGINALTEXT) =lower('").append(basicvalue.trim()).append("')");
	 		 builder.append(" or lower(a.").append("SUBJECTWORD)").append("=lower('").append(basicvalue.trim()).append("')");
			// builder.append(" or lower(a.SUBJECTWORDENG) =lower('").append(basicvalue.trim()).append("')");
	  		 builder.append(" or lower(a.").append("KEYWORD)").append("=lower('").append(basicvalue.trim()).append("')");
			// builder.append(" or lower(a.KEYWORDENG) =lower('").append(basicvalue.trim()).append("')");
			 builder.append(" or lower(a.AUTHOR) =lower('").append(basicvalue.trim()).append("')");
			 //builder.append(" or lower(a.YEARSTR) =lower('").append(basicvalue.trim()).append("')");
			 builder.append(" or lower(a.PERIOD) =lower('").append(basicvalue.trim()).append("')");
			 builder.append(" or lower(a.BOOKCD) =lower('").append(basicvalue.trim()).append("')");
			 builder.append(" or lower(a.FUNDNAME) =lower('").append(basicvalue.trim()).append("')");
			 builder.append(" or lower(a.FUNDTYPE) =lower('").append(basicvalue.trim()).append("')"); 
			 builder.append(" or lower(a.TCMNAME) =lower('").append(basicvalue.trim()).append("'))");
		 }
		 return builder.toString();
	 }
	 /**
	  * 全库高级检索
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  */
	 private ModelAndView advSearch(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap){  
	     Map paramMap = this.advSearchPrepare(request); 
		 String orderName = (String)paramMap.get("orderName");
		 String orderNum = (String)paramMap.get("orderNum"); 
		 String keyword = (String)paramMap.get("keyword");
		 StringBuffer allfullsql = (StringBuffer)paramMap.get("allfullsql");
		 logger.debug("allfullsql:" + allfullsql);
// 		 String orderName = request.getParameter("orderName");//排序字段
//		 String orderNum = request.getParameter("orderNum");//排序方式
//		 String searchtype = request.getParameter("searchtype");//排序方式
//		 String datatypestr = request.getParameter("datatype");//数据范围
//		 String keywordstr = request.getParameter("keyword");//关键词
// 		 String distype = request.getParameter("distype");//疾病类型
//		 String startyear = request.getParameter("startyear_adv");//起始年份
//		 String endyear = request.getParameter("endyear_adv");//起始年份  
//		 request.setAttribute("orderName", orderName); 
//		 request.setAttribute("orderNum", orderNum); 
//		 request.setAttribute("searchtype", searchtype); 
//		 StringBuffer orderByStr = new StringBuffer(" order by ");
//		 if(StringUtils.isNotBlank(orderName)){
//		    	if("1".equals(orderNum)){
//		    		orderByStr.append(orderName).append(" asc");
//		    	}
//		    	if("2".equals(orderNum)){
//		    		orderByStr.append(orderName).append(" desc");
//		    	}
//		  }else{
//		    	orderByStr.append("a.title").append(" desc");
//		    	orderName = "a.title";
//		    	orderNum = "2";
//		  }
//		 StringBuffer allfullsql= new StringBuffer();
//		 allfullsql.append("select a.* from SEARCHMVIEW a where 1=1    ");
//		 String[] datatypes = null;
// 		 if(null != datatypestr && !"".equals(datatypestr)){
//			 datatypes = datatypestr.split(",");
//		 }
// 		 if(null != datatypes && datatypes.length >0){
//  			  int len = datatypes.length;
// 			  if(len == 1){
// 				 allfullsql.append("  and  a.DATATYPE=").append(datatypes[0]);
// 				 System.out.println("000:" + datatypes[0]);
// 			  }else  if(len == 2){
// 				 System.out.println("000:" + datatypes[0]);
// 		 		 System.out.println("000:" + datatypes[1]); 
// 				 allfullsql.append("  and  (a.DATATYPE =");
// 				 allfullsql.append(datatypes[0]);
// 				 allfullsql.append(" or ");
// 				 allfullsql.append(" a.DATATYPE =");
// 				 allfullsql.append(datatypes[1]);
// 				 allfullsql.append(" ) ");
// 			  }else  if(len == 3){
// 				 System.out.println("000:" + datatypes[0]);
// 		 		 System.out.println("000:" + datatypes[1]);
// 		 		 System.out.println("000:" + datatypes[2]);
//  				 allfullsql.append("  and (a.DATATYPE =");
//  				 allfullsql.append(datatypes[0]);
//  				 allfullsql.append(" or ");
//  				 allfullsql.append(" a.DATATYPE =");
//  				 allfullsql.append(datatypes[1]);
//  				 allfullsql.append("  or ");
//  				 allfullsql.append(" a.DATATYPE =");
// 				 allfullsql.append(datatypes[2]);
//  				 allfullsql.append(" ) ");
//  			  } 
//		 }else{
//			 allfullsql.append("  and  a.DATATYPE=0 ");
//		 }
// 		
//		 if(StringUtils.isNotEmpty(distype)){
//			 if(!"0".equals(distype)){
//				 allfullsql.append("  and  a.DISNAME='").append(distype).append("' ");
//			 } 
//		 }
//		 if(StringUtils.isNotEmpty(startyear)){
//			 allfullsql.append("  and  to_date(substr(a.YEARSTR,0,4),'yyyy')>=").append("to_date("+startyear+",'yyyy') ");
//		 }
//		 if(StringUtils.isNotEmpty(endyear)){
//			 allfullsql.append("  and  to_date(substr(a.YEARSTR,0,4),'yyyy')<=").append("to_date("+endyear+",'yyyy') ");
//		 }
//		 
// 		 StringBuffer keywordbuffer = new StringBuffer();
//		 //拼接sql
// 		 
// 		 StringBuffer conditionsql = new StringBuffer();
// 		 conditionsql.append(createSql(request,"txt_1",null,keywordbuffer));
// 		 conditionsql.append(createSql(request,"txt_2",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_3",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_4",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_5",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_6",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_7",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_8",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_9",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_10",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_11",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_12",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_13",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_14",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_15",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_16",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_17",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_18",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_19",null,keywordbuffer));
//		 System.out.println("conditionsql:" + conditionsql);
//		 if(!"".equals(conditionsql.toString())){ 
//			 allfullsql.append(" and ");
//			 allfullsql.append("(");
//			 allfullsql.append(conditionsql.substring(4,conditionsql.length()));
//			 allfullsql.append(") ");
//		 }
//		 allfullsql.append(orderByStr); 
//		//翻页时使用从页面传过来的关键词
//		 if("".equals(keywordbuffer.toString())&&StringUtils.isNotEmpty(keywordstr)){
//			 keywordbuffer.append(keywordstr);
//		 }
////		 
//		 String keyword = keywordbuffer.toString(); 
//	     if(keyword.endsWith("|")){
//	    	 keyword = keyword.substring(0,keyword.length()-1);
//	     }
		 Map conditionmap = new HashMap();
         conditionmap.put("orderName", orderName);
         conditionmap.put("orderNum", orderNum);  
         conditionmap.put("searchtype", orderNum);  
         conditionmap.put("searchtype", "advsearch");   
         conditionmap.put("keyword", keyword);
//         String sql = "select * from ("+allfullsql+")  where 1=1  ";
//         if(StringUtils.isNotEmpty(datatype)&&!"0".equals(datatype)){
//        	 sql = sql + " and datatype="+datatype;
//         }
         logger.debug("allfullsql:" + allfullsql);
		 QueryPage qp = new QueryPage(request,request.getContextPath()+"/search/dosearch.do",allfullsql.toString(),conditionmap); 
//	     
	     qp.query();  
	     String pagenum =  qp.getCurrentPageNo() + "";
	     String pagecount = qp.getPerPageCount() + "";
	     modelMap.put("pagenum", pagenum);
	     modelMap.put("pagecount", pagecount);
	     modelMap.put("pagestr", qp.getPageStr());
	     modelMap.put("datalist", qp.getDataList());
	     modelMap.put("onesql", allfullsql.toString()); 
	     modelMap.put("searchtype", "advsearch");  	  
	     modelMap.put("keyword", keyword);
	     DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
	     String groupsql = "select datatype,count(*) as countnum from (" + qp.getSearchSql() + ") group by datatype"; 
	     List groupList = dbo.queryList(groupsql, null);
	     Map groupMap = new HashMap();
	     for(int j = 0;j<groupList.size();j++){
	    	 Map data = (Map)groupList.get(j);
	    	 String key = (String)data.get("datatype");
	    	 String count = data.get("countnum")+"";
	    	 groupMap.put(key, count);
	    	 
	     }
	     modelMap.put("continfo", groupMap);
	     modelMap.put("allfullsql", allfullsql.toString()); 
		return new ModelAndView("app/search/resultlist",modelMap);
	 }
	 private Map advSearchPrepare(HttpServletRequest request){
		 try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
		 
		}  

		 Map paramMap = new HashMap();
		 String orderName = request.getParameter("orderName");//排序字段
		 String orderNum = request.getParameter("orderNum");//排序方式
		 String searchtype = request.getParameter("searchtype");//排序方式
		 String datatypestr = request.getParameter("datatype");//数据范围
		 String keywordstr = request.getParameter("keyword");//关键词
 		 String startyear = request.getParameter("startyear_adv");//起始年份
		 String endyear = request.getParameter("endyear_adv");//起始年份  
		 String disnamestr = request.getParameter("disnamestr");//起始年份  
		 
		 request.setAttribute("orderName", orderName); 
		 request.setAttribute("orderNum", orderNum); 
		 request.setAttribute("searchtype", searchtype); 
		 StringBuffer orderByStr = new StringBuffer(" order by ");
		 if(StringUtils.isNotBlank(orderName)){
		    	if("1".equals(orderNum)){
		    		orderByStr.append(orderName).append(" asc");
		    	}
		    	if("2".equals(orderNum)){
		    		orderByStr.append(orderName).append(" desc");
		    	}
		  }else{
		    	orderByStr.append("a.id").append(" desc");
		    	orderName = "a.id";
		    	orderNum = "2";
		  }
		 StringBuffer allfullsql= new StringBuffer();
		 allfullsql.append("select a.* from SEARCHMVIEW a where 1=1    ");
		 String[] datatypes = null;
 		 if(null != datatypestr && !"".equals(datatypestr)){
			 datatypes = datatypestr.split(",");
		 }
 		 System.out.println("datatypestr:" + datatypestr);
 		 if(null != datatypes && datatypes.length >0){
  			  int len = datatypes.length;
 			  if(len == 1){
 				 allfullsql.append("  and  a.DATATYPE=").append(datatypes[0]);
 				 System.out.println("000:" + datatypes[0]);
 			  }else  if(len == 2){
 				 System.out.println("000:" + datatypes[0]);
 		 		 System.out.println("000:" + datatypes[1]); 
 				 allfullsql.append("  and  (a.DATATYPE =");
 				 allfullsql.append(datatypes[0]);
 				 allfullsql.append(" or ");
 				 allfullsql.append(" a.DATATYPE =");
 				 allfullsql.append(datatypes[1]);
 				 allfullsql.append(" ) ");
 			  }else  if(len == 3){
 				 System.out.println("000:" + datatypes[0]);
 		 		 System.out.println("000:" + datatypes[1]);
 		 		 System.out.println("000:" + datatypes[2]);
  				 allfullsql.append("  and (a.DATATYPE =");
  				 allfullsql.append(datatypes[0]);
  				 allfullsql.append(" or ");
  				 allfullsql.append(" a.DATATYPE =");
  				 allfullsql.append(datatypes[1]);
  				 allfullsql.append("  or ");
  				 allfullsql.append(" a.DATATYPE =");
 				 allfullsql.append(datatypes[2]);
  				 allfullsql.append(" ) ");
  			  } 
		 }else{
			 allfullsql.append("  and  a.DATATYPE=0 ");
		 }
 		
 		if(StringUtils.isNotEmpty(disnamestr)){
			 String[] disnamearr = disnamestr.split(",");
			 if(null != disnamearr && disnamearr.length == 1){
				 allfullsql.append("  and  a.DISNAME='").append(disnamearr[0]).append("' ");
			 }
			 if(null != disnamearr && disnamearr.length == 2){
				 allfullsql.append("  and  (a.DISNAME='").append(disnamearr[0]).append("' ");
				 allfullsql.append("  or  a.DISNAME='").append(disnamearr[1]).append("') ");
			 }
			  
		 }
		 if(StringUtils.isNotEmpty(startyear)){
			 allfullsql.append("  and  to_date(substr(a.YEARSTR,0,4),'yyyy')>=").append("to_date("+startyear+",'yyyy') ");
		 }
		 if(StringUtils.isNotEmpty(endyear)){
			 allfullsql.append("  and  to_date(substr(a.YEARSTR,0,4),'yyyy')<=").append("to_date("+endyear+",'yyyy') ");
		 }
		 
 		 StringBuffer keywordbuffer = new StringBuffer();
		 //拼接sql
 		 
 		 StringBuffer conditionsql = new StringBuffer();
 		 conditionsql.append(createSql(request,"txt_1",null,keywordbuffer));
 		 conditionsql.append(createSql(request,"txt_2",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_3",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_4",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_5",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_6",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_7",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_8",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_9",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_10",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_11",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_12",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_13",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_14",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_15",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_16",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_17",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_18",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_19",null,keywordbuffer));
		 System.out.println("conditionsql:" + conditionsql);
		 if(!"".equals(conditionsql.toString())){ 
			 allfullsql.append(" and ");
			 allfullsql.append("(");
			 allfullsql.append(conditionsql.substring(4,conditionsql.length()));
			 allfullsql.append(") ");
		 }
		 allfullsql.append(orderByStr); 
		//翻页时使用从页面传过来的关键词
		 if("".equals(keywordbuffer.toString())&&StringUtils.isNotEmpty(keywordstr)){
			 keywordbuffer.append(keywordstr);
		 }
//		 
		 String keyword = keywordbuffer.toString(); 
	     if(keyword.endsWith("|")){
	    	 keyword = keyword.substring(0,keyword.length()-1);
	     }
	     
	     paramMap.put("allfullsql", allfullsql); 
	     paramMap.put("orderName", orderName);
	     paramMap.put("orderNum", orderNum); 
	     paramMap.put("keyword", keyword); 
		 return paramMap;
	 }

	 private String createSql(HttpServletRequest request,String cname,StringBuffer buffer,StringBuffer keywordbuffer){
		 StringBuffer sqlbuffer = new StringBuffer();
		 //值
		 String c_value = cname+"_value";
		 //逻辑关系，并且 或者
		 String c_logical = cname+"_logical";
		 //字段的名字
		 String c_sel = cname+"_sel";
		 //精确或模糊
		 String c_special = cname+"_special";
		 
		 String cvalue = request.getParameter(c_value);
		 String clogical = request.getParameter(c_logical);
		 String csel = request.getParameter(c_sel);
		 String cspecial = request.getParameter(c_special);
		 
		 String logicalname = "";
		 
		 String colname = (String)CONSTANTMAP.get(csel);
//		 if(null != colname){
//			 if("1".equals(clogical)){
//				 logicalname = " OR ";
//				 
//			 }else{
//				 logicalname = " AND ";
//			 }
//			// buffer.append(colname ).append("“").append(cvalue).append("”&nbsp;").append(logicalname).append("&nbsp;");
//			 keywordbuffer.append(cvalue).append("|");
//		 }
		 keywordbuffer.append(cvalue).append("|");
		 request.setAttribute(c_value, cvalue);
		 request.setAttribute(c_logical, c_logical);
		 request.setAttribute(c_sel, c_sel);
		 request.setAttribute(c_special, c_special);
		 //logger.debug("value:::" + clogical + "," + csel + "," + cvalue + "," + cspecial);
//		 if(StringUtils.isEmpty(cspecial))
//			 cspecial = "1";//默认为模糊检索
		 if(null == cvalue || StringUtils.isEmpty(cvalue)){//查询条件为空时返回空
			 return "";
		 }
		 logger.debug("clogical:" + clogical);
		 logger.debug("c_sel:" + c_sel);
		 if("0".equals(clogical)){
			 //0 and 关系  1：或者关系
			 sqlbuffer.append(" and "); 
		 }else if("1".equals(clogical)){
			 //0 and 关系  1：或者关系
			 sqlbuffer.append(" or "); 
		 }else{
			 sqlbuffer.append(" and "); 
		 }
		 sqlbuffer.append("lower(").append(csel).append(")");
		 if("0".equals(cspecial)){
			 //0 精确  1：模糊
			 sqlbuffer.append(" =lower('"); 
			 sqlbuffer.append(cvalue.trim());
			 sqlbuffer.append("')");
		 }
		 if("1".equals(cspecial)){
			//0 精确  1：模糊
			 sqlbuffer.append(" like '%'||lower('"); 
			 sqlbuffer.append(cvalue.trim());
			 sqlbuffer.append("')||'%'");
		 }
		 return sqlbuffer.toString();
	 }
	 /**
	  * 按年份分组
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/yeargroup.do", method = RequestMethod.GET)   
     public void yeargroup(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		  logger.debug("===============================:::::::::::::");
		  Map pmap = getParamMap(request);
		  StringBuffer allfullsql = (StringBuffer)pmap.get("allfullsql");
		  String sql = "select * from (select pubyear,count(*) as countnum from (select substr(yearstr,0,4) as pubyear,id from (" + allfullsql + ") where yearstr is not null) group by pubyear) order by countnum desc";
		  DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
		  List datalist = dbo.queryList(sql, null);
		  StringBuffer contentBuffer = new StringBuffer();
		  int count = 0;
		  if(datalist.size() >0){
			  for(int i = 0;i<datalist.size();i++){
				  count++;
				  if(count >= 15)
					  break;
				  Map data = (Map)datalist.get(i);
				  String yearstr = (String)data.get("pubyear");
				  String countstr = data.get("countnum")+"";
				 // <li><a href="#">2012</a><span>3625</span></li>
				  contentBuffer.append("<li><a href=\"");
				  contentBuffer.append("#");
				  contentBuffer.append("\">");
				  contentBuffer.append(yearstr);
				  contentBuffer.append("</a><span><font color=red>");
				  contentBuffer.append(countstr);
				  contentBuffer.append("</font></span></li>"); 
			  }
		  }else{
			  contentBuffer.append("<li><font color=red>");
			  contentBuffer.append("没有符合查询条件的数据");
			  contentBuffer.append("</font></li>");
		  }
		  PrintWriter out = response.getWriter();
	      out.print(contentBuffer.toString());
	      out.flush();
	      out.close();
//		  return new ModelAndView("app/search/detail",modelMap);
		 
	 }
	private Map getParamMap(HttpServletRequest request) {
		  Map pmap = null; 
		  String searchtype = request.getParameter("searchtype");
		  System.out.println("searchtype:" + searchtype);
		  if("advsearch".equals(searchtype)){
			  pmap = this.advSearchPrepare(request);
		  }else{
			  pmap = this.basicSearchPrepare(request); 
		  }
		return pmap;
	}
	 /**
	  * 按期刊分组
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/pernamegroup.do", method = RequestMethod.GET)   
     public void pernamegroup(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		  Map pmap = getParamMap(request);
		  StringBuffer allfullsql = (StringBuffer)pmap.get("allfullsql");
		  String sql = "select * from (select PERIODICALNAME,count(*) as countnum from  (" + allfullsql + ") where PERIODICALNAME is not null group by PERIODICALNAME) order by countnum desc";
		  DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
		  List datalist = dbo.queryList(sql, null);
		  StringBuffer contentBuffer = new StringBuffer();
		  int count = 0;
		  if(datalist.size() >0){
		  for(int i = 0;i<datalist.size();i++){
			  count++;
			  if(count >= 15)
				  break;
			  Map data = (Map)datalist.get(i);
			  String yearstr = (String)data.get("PERIODICALNAME");
			  String countstr = data.get("countnum")+"";
			 // <li><a href="#">2012</a><span>3625</span></li>
			  contentBuffer.append("<li><a href=\"");
			  contentBuffer.append("#");
			  contentBuffer.append("\">");
			  contentBuffer.append(yearstr);
			  contentBuffer.append("</a><span><font color=red>");
			  contentBuffer.append(countstr);
			  contentBuffer.append("</font></span></li>"); 
		  }
		  
				}else{
					  contentBuffer.append("<li><font color=red>");
					  contentBuffer.append("没有符合查询条件的数据");
					  contentBuffer.append("</font></li>");
				  }
		  PrintWriter out = response.getWriter();
	      out.print(contentBuffer.toString());
	      out.flush();
	      out.close();
		  //return new ModelAndView("app/search/detail",modelMap);
		 
	 }
	 
	 /**
	  * 数据导出
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/resultexport.do", method = RequestMethod.GET)   
     public ModelAndView resultexport(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		  String pid = request.getParameter("pid");
		  if(StringUtils.isNotEmpty(pid)){ 
			  SchdChnpaper obj = (SchdChnpaper)this.searchService.findByID(SchdChnpaper.class, new Long(pid));
			  modelMap.put("obj", obj);
		  }
		  return new ModelAndView("app/search/detail",modelMap);
		 
	 }
	 /**
	  * 查看详细题录信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/viewdetail.do", method = RequestMethod.GET)   
     public ModelAndView viewdetail(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		  String pid = request.getParameter("pid");
		  if(StringUtils.isNotEmpty(pid)){ 
			  Searchmview obj = (Searchmview)this.searchService.findByID(Searchmview.class, new Long(pid));
			  modelMap.put("obj", obj);
		  }
		  return new ModelAndView("app/search/detail",modelMap);
		 
	 }
//	
//	 private static String cutStr(String str){
//		 if(str.lastIndexOf(',') != -1){
//			 str = str.substring(0, str.length()-1);
//		 }
//		 return str;
//	 }
//	 
	 static {
		 CONSTANTMAP.put("TITLE","标题");
		 CONSTANTMAP.put("TITLEN","标题");
		 CONSTANTMAP.put("PERIODICALNAME","刊名");
		 CONSTANTMAP.put("PERIODICALNAMEENG","刊名");
		 CONSTANTMAP.put("BOOKNAME","书籍名称");
		 CONSTANTMAP.put("AUTHOR","作者");
		 CONSTANTMAP.put("AUTHOREN","作者");
		 CONSTANTMAP.put("AUTHORUNIT","作者单位");
		 CONSTANTMAP.put("AUTHORADDRESS","作者通讯地址");
		 CONSTANTMAP.put("KEYWORD","关键词");
		 CONSTANTMAP.put("KEYWORDENG","关键词");
		 CONSTANTMAP.put("SUBJECTWORD","主题词");
		 CONSTANTMAP.put("SUBJECTWORDENG","主题词");
		 CONSTANTMAP.put("ABSTRACT","摘要");
		 CONSTANTMAP.put("ABSTRACTENG","摘要");
		 CONSTANTMAP.put("ORIGINALTEXT","原文文本");
		 CONSTANTMAP.put("LANGUAGE","语种");
		 CONSTANTMAP.put("DOCUMENTTYPE","文献类型");
		 CONSTANTMAP.put("CLASSNO","分类号");
		 CONSTANTMAP.put("FUNDSTR","资助情况");
		 CONSTANTMAP.put("YEARSTR","年份");
		 CONSTANTMAP.put("VOLUME","卷");
		 CONSTANTMAP.put("PERIOD","期");
		 CONSTANTMAP.put("PAGENO","页码");
		 CONSTANTMAP.put("VOLUMESECTION","卷册章节");
		 CONSTANTMAP.put("FUNDTYPE","资助类别");
		 CONSTANTMAP.put("COMFROM","文献来源");
		 CONSTANTMAP.put("AREASTR","国家\\省市");
		 CONSTANTMAP.put("CWNUM","参文数");
		 CONSTANTMAP.put("ISSNSTR","ISSN编号");
		 CONSTANTMAP.put("CONTRYCODE","国内代码");
		 CONSTANTMAP.put("CODESTR","内部代码");
		 CONSTANTMAP.put("PUBLISHAREA","出版地");
		 CONSTANTMAP.put("IMPRESSWORD","特征词");
		 CONSTANTMAP.put("UPDATEDATE","更新日期");
		 CONSTANTMAP.put("AUTHORABSTRACT","著者文摘");
		 CONSTANTMAP.put("FUNDNAME","基金");
		 CONSTANTMAP.put("CASTR","CA");
		 CONSTANTMAP.put("USERSUBJECT","人名主题");
		 CONSTANTMAP.put("TCMNAME","中医病名");
		 CONSTANTMAP.put("BOOKVERSION","书籍版本");
		 CONSTANTMAP.put("INPUTUSER","录入人"); 
		 CONSTANTMAP.put("BOOKCD","朝代"); 
	 }
		@RequestMapping("/search/exportAllData.do")   
		public ModelAndView exportAllData(HttpServletRequest request,
				HttpServletResponse response) throws Exception { 
			try  {
				String ids = request.getParameter("ids");
				if(StringUtils.isEmpty(ids)){
					return null;
				}else{
					ids = ids.substring(0,ids.length()-1);
				}
				String path = this.exportTxtData(ids);
				System.out.println("message::" + path );
				//  path是指欲下载的文件的路径。 
 				File file  =   new  File(path);
				String filename  =  file.getName();
				int fileLength = (int)file.length();
				int                 length   = 0;
		        ServletOutputStream op       = response.getOutputStream();
		        ServletContext      context  = request.getSession().getServletContext();
		        String              mimetype = context.getMimeType( filename );
		        byte[]   byteContents   =   new   byte[fileLength];   
		        FileInputStream fis   =   new   FileInputStream(file);   
		        int   retcd   =   fis.read(byteContents);   
		        fis.close();    
		        logger.debug("mimetype:" + mimetype);
		        response.setContentType(mimetype == null?"text/plain":mimetype );
		        response.setContentLength( retcd );
		        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("gb2312"),"ISO-8859-1") + "\"" );
		        op.write(byteContents,0,retcd); 
		        op.close();
	    }  catch  (IOException ex) {
	        ex.printStackTrace();
	    }
			return null;  
		} 
		/**
		 * 生成题录数据文件（TXT）
		 * @return 生成的文件的路径
		 */
		public String exportTxtData(String rids){
			String message = "false";
			 try {
				 String tempFilepath = SystemUtil.getWebappRoot().toString();
				 tempFilepath = tempFilepath.replace("\\", "/") + "/temp";
				 System.out.println("tempFilepath::" + tempFilepath );
				 File tempfile = new File(tempFilepath);
				 if(!tempfile.exists()){
					 tempfile.mkdirs();
				 }
				 String destfile = tempFilepath + "/" + "export"+System.currentTimeMillis()+".txt";
				 FileOutputStream outSTr = null;      
				 BufferedOutputStream Buff = null;    
				      
				 String tab = "  ";      
				 String enter = "\r\n";      
				 List  accList = DBMgr.getDbUtilInst().queryList("select * from SEARCHMVIEW where id in("+rids+") order by id",null);
	
				   StringBuffer write ;      
				    try {      
				        outSTr = new FileOutputStream(new File(destfile));      
				        Buff = new BufferedOutputStream(outSTr);      
				        for(int i=0; i<accList.size(); i++){
							Map data = (Map)accList.get(i);      
				            write = new StringBuffer(); 
				            String temp0 = null2str((String)data.get("DISNAME"));
				            if(!"".equals(temp0))
				            	write.append("病名:"+temp0+enter); 
				            String temp1 = null2str((String)data.get("CLASSNO"));
				            if(!"".equals(temp1))
				            	write.append("分类号:"+temp1+enter); 
				            String temp2 = null2str((String)data.get("TITLE"));
				            if(!"".equals(temp2))
				            	write.append("标题:"+temp2+enter); 
				            String temp3 = null2str((String)data.get("AUTHOR"));
				            if(!"".equals(temp3))
							write.append("作者:"+temp3+enter);
				            String temp4 = null2str((String)data.get("AUTHORUNIT"));
				            if(!"".equals(temp4))
				            	write.append("作者单位:"+temp4+enter);
				            String temp5 = null2str((String)data.get("AREASTR"));
				            if(!"".equals(temp5))
							write.append("国家\\省市:"+temp5+enter);
				            String temp6 = null2str((String)data.get("CWNUM"));
				            if(!"".equals(temp6))
				            	write.append("参文数:"+temp6+enter);
				            String temp7 = null2str((String)data.get("PERIODICALNAME"));
				            if(!"".equals(temp7))
							    write.append("刊名:"+temp7+enter);
				            String temp8 = null2str((String)data.get("YEARSTR"));
				            if(!"".equals(temp8))
				            	write.append("年份:"+temp8+enter);
				            String temp9 = null2str((String)data.get("VOLUME"));
				            if(!"".equals(temp1))
							write.append("卷:"+temp9+enter);
				            String temp10 = null2str((String)data.get("PERIOD"));
				            if(!"".equals(temp10))
							write.append("期:"+temp10+enter); 
				            String temp11 = null2str((String)data.get("PAGENO"));
				            if(!"".equals(temp11))
				            	write.append("页码:"+temp11+enter);
				            String temp12 = null2str((String)data.get("ISSNSTR"));
				            if(!"".equals(temp12))
				            	write.append("ISSN:"+temp12+enter); 
				            String temp13 = null2str((String)data.get("CONTRYCODE"));
				            if(!"".equals(temp13)) 
				            	write.append("国别:"+temp13+enter);
				            String temp14 = null2str((String)data.get("CODESTR"));
				            if(!"".equals(temp14))  
				            	write.append("地区:"+temp14+enter);
				            String temp15 = null2str((String)data.get("PUBLISHAREA"));
				            if(!"".equals(temp15)) 
							write.append("出版地:"+temp15+enter);
				            String temp16 = null2str((String)data.get("KEYWORD"));
				            if(!"".equals(temp16)) 
							write.append("关键词:"+temp16+enter);
				            String temp17 = null2str((String)data.get("SUBJECTWORD"));
				            if(!"".equals(temp17)) 
							write.append("主题词:"+temp17+enter);
				            String temp18 = null2str((String)data.get("IMPRESSWORD"));
				            if(!"".equals(temp18)) 
							write.append("特征词:"+temp18+enter);
				            String temp19 = null2str((String)data.get("UPDATEDATE"));
				            if(!"".equals(temp19)) 
							write.append("更新日期:"+temp19+enter);
				            String temp20 = null2str((String)data.get("TITLEN"));
				            if(!"".equals(temp20)) 
				            	write.append("英文标题:"+temp20+enter);
				            String temp21 = null2str((String)data.get("ABSTRACT"));
				            if(!"".equals(temp21)) 
							write.append("摘要:"+temp21+enter);
				            String temp22 = null2str((String)data.get("AUTHORABSTRACT"));
				            if(!"".equals(temp22)) 
							write.append("著者文摘:"+temp22+enter);
				            String temp23 = null2str((String)data.get("DOCUMENTTYPE"));
				            if(!"".equals(temp23)) 
							write.append("文献类型:"+temp23+enter);
				            String temp24 = null2str((String)data.get("FUNDNAME"));
				            if(!"".equals(temp24)) 
							write.append("基金:"+temp24+enter);
				            String temp25 = null2str((String)data.get("LANGUAGE"));
				            if(!"".equals(temp25)) 
							write.append("语种:"+temp25+enter);
				            String temp26 = null2str((String)data.get("USERSUBJECT"));
				            if(!"".equals(temp26)) 
							write.append("人名主题:"+temp26+enter);
				            String temp27 = null2str((String)data.get("CASTR"));
				            if(!"".equals(temp27)) 
							write.append("CA:"+temp27+enter);
				            String temp28 = null2str((String)data.get("PERIODICALNAME"));
				            if(!"".equals(temp28)) 
							write.append("书籍名称:"+temp28+enter); 
				            String temp29 = null2str((String)data.get("TCMNAME"));
				            if(!"".equals(temp29)) 
							write.append("中医病名:"+temp29+enter);
				            String temp30 = null2str((String)data.get("ABSTRACT"));
				            if(!"".equals(temp30)) 
							write.append("原文文本化:"+temp30+enter);
				            String temp31 = null2str((String)data.get("VOLUMESECTION"));
				            if(!"".equals(temp31)) 
							write.append("卷册章节:"+temp31+enter);
				            String temp32 = null2str((String)data.get("BOOKVERSION"));
				            if(!"".equals(temp32)) 
							write.append("书籍版本:"+temp32+enter);
				            String temp33 = null2str((String)data.get("INPUTUSER"));
				            if(!"".equals(temp33)) 
							write.append("录入人:"+temp33+enter);
				            String temp34 = null2str((String)data.get("INPUTDATE"));
				            if(!"".equals(temp34)) 
						    write.append("录入日期:"+temp34+enter); 
				            String temp35 = null2str((String)data.get("BOOKCD"));
				            if(!"".equals(temp35)) 
						    write.append("朝代:"+temp35+enter);      
				            write.append(enter);          
				            Buff.write(write.toString().getBytes("UTF-8")); 
				            
				        }             
				        Buff.flush();      
				        Buff.close();      
				  } catch (Exception e) {      
				        e.printStackTrace();      
				    } finally {      
				        try {      
				           Buff.close();      
				            outSTr.close();      
				        } catch (Exception e) {      
				           e.printStackTrace();      
				        }      
				    }       
					 message = destfile;
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			return message;
			
		}
		private String null2str(String content){
			if(null == content || "null".equalsIgnoreCase(content)){
				return "";
			}
			return content;
		}
}
